package com.atguigu.gmall.item.service.impl;

import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.item.feign.GmallPmsClient;
import com.atguigu.gmall.item.feign.GmallSmsClient;
import com.atguigu.gmall.item.feign.GmallWmsClient;
import com.atguigu.gmall.item.service.ItemService;
import com.atguigu.gmall.item.vo.ItemVo;
import com.atguigu.gmall.pms.api.GmallPmsApi;
import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.pms.vo.ItemGroupVo;
import com.atguigu.gmall.pms.vo.SaleAttrValueVo;
import com.atguigu.gmall.sms.api.GmallSmsApi;
import com.atguigu.gmall.sms.vo.ItemSaleVo;
import com.atguigu.gmall.wms.entity.WareSkuEntity;
import javafx.scene.media.VideoTrack;
import net.bytebuddy.asm.Advice;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.time.temporal.Temporal;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    GmallSmsClient gmallSmsClient;
    @Autowired
    GmallPmsClient gmallPmsClient;
    @Autowired
    GmallWmsClient gmallWmsClient;
    @Autowired
    ExecutorService executorService;
    @Autowired
    TemplateEngine templateEngine;
    @Override
    public ItemVo queryItemVoBySkuId(Long skuId) {
        ItemVo itemVo = new ItemVo();
        //查询sku接口，查询对应的sku
        // 1、根据skuid，查询出sku的相关字段  √
        CompletableFuture<SkuEntity> skuFuture = CompletableFuture.supplyAsync(() -> {
            ResponseVo<SkuEntity> skuEntityResponseVo = gmallPmsClient.querySkuById(skuId);
            SkuEntity skuEntity = skuEntityResponseVo.getData();
            if (skuEntity == null) {
                return null;
            }
            itemVo.setPrice(skuEntity.getPrice());
            itemVo.setTitle(skuEntity.getTitle());
            itemVo.setSubTitle(skuEntity.getSubtitle());
            itemVo.setSkuId(skuEntity.getId());
            itemVo.setWeight(skuEntity.getWeight());
            itemVo.setDefaultImage(skuEntity.getDefaultImage());
            return skuEntity;
        }, executorService);

        // 2、根据cid查询123级分类id √
        CompletableFuture<Void> catesFuture = skuFuture.thenAcceptAsync((skuEntity) -> {
            ResponseVo<List<CategoryEntity>> listResponseVo = gmallPmsClient.queryCategoryEntity123ByCid(skuEntity.getCategoryId());
            List<CategoryEntity> categoryEntityList = listResponseVo.getData();
            if (!CollectionUtils.isEmpty(categoryEntityList)) {
                itemVo.setCategories(categoryEntityList);
            }
        }, executorService);

        //  3、根据品牌id，查询品牌相关的信息 √
        CompletableFuture<Void> brandFuture = skuFuture.thenAcceptAsync((skuEntity) -> {
            ResponseVo<BrandEntity> brandEntityResponseVo = gmallPmsClient.queryBrandById(skuEntity.getBrandId());
            BrandEntity brandEntity = brandEntityResponseVo.getData();
            if (brandEntity != null) {
                itemVo.setBrandId(brandEntity.getId());
                itemVo.setBrandName(brandEntity.getName());
            }
        }, executorService);

        // 4、根据spuid查询出spu相关的信息 √
        CompletableFuture<Void> spuFuture = skuFuture.thenAcceptAsync((skuEntity) -> {
            ResponseVo<SpuEntity> spuEntityResponseVo = gmallPmsClient.querySpuById(skuEntity.getSpuId());
            SpuEntity spuEntity = spuEntityResponseVo.getData();
            if (spuEntity != null) {
                itemVo.setSpuId(spuEntity.getId());
                itemVo.setSpuName(spuEntity.getName());
            }
        }, executorService);

        // 5、根据skuid，查询出sku的images列表 √
        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            ResponseVo<List<SkuImagesEntity>> imagesResponseVo = gmallPmsClient.querySkuImagesByskuId(skuId);
            List<SkuImagesEntity> imagesEntities = imagesResponseVo.getData();
            itemVo.setImages(imagesEntities);
        }, executorService);


        //6、根据skuid，查询出营销相关的信息 √
        CompletableFuture<Void> saleFuture = CompletableFuture.runAsync(() -> {
            ResponseVo<List<ItemSaleVo>> itemSaleinfoResponseVo = gmallSmsClient.getItemSaleInfoBySkuId(skuId);
            List<ItemSaleVo> itemSaleVoList = itemSaleinfoResponseVo.getData();
            itemVo.setSales(itemSaleVoList);
        }, executorService);

        // 7、根据skuid，查询库存信息 √
        CompletableFuture<Void> wareFuture = CompletableFuture.runAsync(() -> {
            ResponseVo<List<WareSkuEntity>> wareResponseVo = gmallWmsClient.queryWareSkuBySkuId(skuId);
            List<WareSkuEntity> wareSkuEntities = wareResponseVo.getData();
            if (!CollectionUtils.isEmpty(wareSkuEntities)) {
                itemVo.setStore(wareSkuEntities.stream().anyMatch(wareSkuEntity -> wareSkuEntity.getStock() - wareSkuEntity.getStockLocked() > 0));
            }
        }, executorService);

        // 8、根据spuid，查询出所有spu销售属性的字段 √
        CompletableFuture<Void> spuAttrValuesFuture = skuFuture.thenAcceptAsync((skuEntity) -> {
            ResponseVo<List<SaleAttrValueVo>> saleAttrValueListResponseVo = gmallPmsClient.querySaleAttrValuesBySpuId(skuEntity.getSpuId());
            List<SaleAttrValueVo> saleAttrValueVoList = saleAttrValueListResponseVo.getData();
            itemVo.setSaleAttrs(saleAttrValueVoList);
        }, executorService);

        // 9、根据skuid，查询出当前sku的销售属性 √
        CompletableFuture<Void> skuAttrValuesFuture = CompletableFuture.runAsync(() -> {
            ResponseVo<List<SkuAttrValueEntity>> saleAttrValuesListResponseVo = gmallPmsClient.querySaleAttrValuesBySkuId(skuId);
            List<SkuAttrValueEntity> skuAttrValueEntityList = saleAttrValuesListResponseVo.getData();
            if (!CollectionUtils.isEmpty(skuAttrValueEntityList)) {
                itemVo.setSaleAttr(skuAttrValueEntityList.stream().collect(Collectors.toMap(
                        SkuAttrValueEntity -> SkuAttrValueEntity.getAttrId(), SkuAttrValueEntity -> SkuAttrValueEntity.getAttrValue()
                )));
            }
        }, executorService);

        // 10、根据spuid查询所有销售属性组合 √
        CompletableFuture<Void> mappingFuture = skuFuture.thenAcceptAsync((skuEntity) -> {
            ResponseVo<String> queryMappingBySpuId = gmallPmsClient.queryMappingBySpuId(skuEntity.getSpuId());
            itemVo.setSkuJsons(queryMappingBySpuId.getData());
        }, executorService);


        // 11、根据spuid查询描述信息 √
        CompletableFuture<Void> spuDescFuture = skuFuture.thenAcceptAsync((skuEntity) -> {
            ResponseVo<SpuDescEntity> spuDescEntityResponseVo = gmallPmsClient.querySpuDescById(skuEntity.getSpuId());
            SpuDescEntity spuDescEntity = spuDescEntityResponseVo.getData();
            itemVo.setSpuImages(Arrays.asList(StringUtils.split(spuDescEntity.getDecript(), ",")));
        }, executorService);

        // 12、根据cid，spuid，skuid查询组及组下规格参数和值 √
        CompletableFuture<Void> groupFuture = skuFuture.thenAcceptAsync((skuEntity) -> {
            ResponseVo<List<ItemGroupVo>> ItemGroupVoListResponseVo = gmallPmsClient.queryAttrGroupBySpuIdAndCidAndSkuId(skuEntity.getCategoryId(), skuId, skuEntity.getSpuId());
            List<ItemGroupVo> itemGroupVoList = ItemGroupVoListResponseVo.getData();
            itemVo.setGroups(itemGroupVoList);
        }, executorService);

        CompletableFuture.allOf(catesFuture,brandFuture,spuFuture,imagesFuture,saleFuture,
                wareFuture,spuAttrValuesFuture,skuAttrValuesFuture,mappingFuture,spuDescFuture,groupFuture).join();
        staticHtml(itemVo);
        return itemVo;
    }

    private void staticHtml(ItemVo itemVo){
        executorService.execute(()->{
            try ( PrintWriter printWriter = new PrintWriter("D:\\shangguigu\\尚硅谷java课件\\第9部分：电商项目资料\\谷粒商城\\item_static\\"+itemVo.getSkuId()+".html")){
                Context context = new Context();
                context.setVariable("itemVo",itemVo);
                templateEngine.process("item", context,printWriter);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        });
    }


}
